﻿/*******************************************
 * @Copyright: (C) 2021 WeiLaiZhiAn All rights reserved.
 * @
 * @Author: HaoNan.Wang
 * @Date: 2021-11-12 15:53:22
 * @
 * @LastEditors: HaoNan.Wang
 * @LastEditTime: 2021-11-12 15:53:22
 * @Description: 可把任何类包装成线程安全的全局单例类，出口默认智能指针
 * @Note:
 * @FilePath: \baize_client-agent\src\common\utilities\singleton.h
 *******************************************/

#ifndef MAGIC_SINGLETON_H_
#define MAGIC_SINGLETON_H_

#include <memory>
#include <mutex>


template<typename T>
class Singleton {
public:
    template<typename... Args>
    static T& instance(Args&&... args) {
        std::call_once(init_flag_, [&args...] {
            instance_.reset(new T(std::forward<Args>(args)...));
            });
        return *instance_;
    }

public:
    static std::unique_ptr<T> instance_;
    static std::once_flag init_flag_;

    Singleton() = default;
    ~Singleton() = default;
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    Singleton(Singleton&&) = default;
    Singleton& operator=(Singleton&&) = default;
};

template<typename T>
std::unique_ptr<T> Singleton<T>::instance_;
template<typename T>
std::once_flag Singleton<T>::init_flag_;

#endif  // MAGIC_SINGLETON_H_
